<template>
  <div :class="[prefixCls, { fullscreen }]">
    <Upload
        name="file"
        multiple
        @change="handleChange"
        :action="uploadUrl"
        :showUploadList="false"
        :data="getBizData()"
        :headers="headers"
        accept=".jpg,.jpeg,.gif,.png,.webp"
    >
      <a-button type="primary" v-bind="{ ...getButtonProps }">
        图片上传
      </a-button>
    </Upload>
  </div>
</template>
<script lang="ts">
import {computed, defineComponent} from 'vue';
import {uploadUrl} from '@/api/common/api'

import {Upload} from 'ant-design-vue';
import {getFileAccessHttpUrl, getHeaders} from '@/utils/compUtils';

export default defineComponent({
  name: 'TinymceImageUpload',
  components: {Upload},
  props: {
    fullscreen: {
      type: Boolean,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['uploading', 'done', 'error'],
  setup(props, {emit}) {
    let uploading = false;
    const headers = getHeaders();

    const prefixCls = "jeecg-tinymce-img-upload";

    //update-begin-author:taoyan date:2022-5-13 for: 富文本上传图片不支持

    function getBizData() {
      return {
        biz: 'jeditor',
        jeditor: '1',
      };
    }

    const getButtonProps = computed(() => {
      const {disabled} = props;
      return {
        disabled,
      };
    });

    function handleChange(info: Recordable) {
      const file = info.file;
      const status = file?.status;
      //const url = file?.response?.url;
      const name = file?.name;

      if (status === 'uploading') {
        if (!uploading) {
          emit('uploading', name);
          uploading = true;
        }
      } else if (status === 'done') {
        //update-begin-author:taoyan date:2022-5-13 for: 富文本上传图片不支持
        let realUrl = getFileAccessHttpUrl(file.response.message);
        emit('done', name, realUrl);
        //update-end-author:taoyan date:2022-5-13 for: 富文本上传图片不支持
        uploading = false;
      } else if (status === 'error') {
        emit('error');
        uploading = false;
      }
    }

    return {
      handleChange,
      uploadUrl,
      headers,
      getBizData,
      getButtonProps,
      prefixCls
    };
  },
});
</script>
<style lang="less" scoped>
@prefix-cls: ~'jeecg-tinymce-img-upload';

.@{prefix-cls} {
  position: absolute;
  top: 4px;
  right: 10px;
  z-index: 20;

  &.fullscreen {
    position: fixed;
    z-index: 10000;
  }
}
</style>
